
<template>
  <div class="app-container">

    <div class="filter-container">
      
      <el-button v-if="this.listQuery.nodeId != undefined && this.total == 0 && this.listQuery.adoptInfo == 1" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        创建整改报告书
      </el-button>
     
     </div> 

     <div style="color:red; font-weight: 700;">整改报告书</div>

    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">
      <el-table-column min-width="100px" label="编号">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span></template>
      </el-table-column>
      <el-table-column min-width="100px" label="建议措施">
        <template slot-scope="scope">
          <span>{{ scope.row.adoptId.suggestMeasure }}</span></template>
      </el-table-column>
      <el-table-column min-width="120px" label="整改措施">
        <template slot-scope="scope">
          <span>{{ scope.row.rectifyMeasure }}</span></template>
      </el-table-column>
      <el-table-column class-name="status-col" label="附件" width="110">
        <template slot-scope="scope">
          <el-button v-if="scope.row.fileMeasure== 1" type="primary" size="small" @click="handlegetFile(scope.row)">附件</el-button>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" label="整改情况">
        <template slot-scope="scope">
          <span v-if="scope.row.rectifySituation==0" style="color:green;" >未整改</span>
          <span v-if="scope.row.rectifySituation==2" style="color:blue;" >审批中..</span>
          <span v-if="scope.row.rectifySituation==-1" style="color:orange;" >驳回</span>
          <span v-if="scope.row.rectifySituation==1" style="color:red;">整改完成</span></template>
      </el-table-column>
      <el-table-column min-width="120px" label="审批时间">
        <template slot-scope="scope">
          <span>{{ scope.row.approvalDate }}</span></template>
      </el-table-column>
      <el-table-column min-width="100px" label="审批意见">
        <template slot-scope="scope">
          <span>{{ scope.row.approvalOpinion }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230">
        <template slot-scope="scope">
          <el-button v-if="scope.row.rectifySituation==-1" type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.rectifySituation==-1" type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="hidden" label="编号" prop="id" readonly>
          <el-input v-model="temp.id" readonly />
        </el-form-item>
        <el-form-item v-if="hidden" label="建议措施" prop="adoptId">
          <el-input v-model="suggestMeasure1" readonly />
        </el-form-item>
        <el-form-item label="整改措施" :required="!isRequired" prop="rectifyMeasure">
          <el-input v-model="temp.rectifyMeasure" />
        </el-form-item>
        <el-form-item label="附件上传">
          <ul>
            <div style="margin-left:100px"> 
              <el-upload
                v-model="file"
                class="upload-demo"
                action="http://localhost:8080/ehs_files/upload"
                :on-change="handleChange"
                :on-success="uploadfile"
              ><el-button size="big" type="primary">点击上传</el-button>
              </el-upload>
            </div>
          </ul>.
        </el-form-item>
        </el-form> 
        
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ElDragSelect from '@/components/DragSelect' // base on element-ui
import MarkdownEditor from '@/components/MarkdownEditor'
import { rectificationList, addRectification, editRectification, deleteRectification} from '@/api/rectification'
import Sortable from 'sortablejs'
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { getuserbyemp } from '@/api/user'
import checkPermission from '@/utils/permission'
import { getFileName } from '@/api/file'
export default {
  name: 'Rectification',
  components: { },
  directives: { waves },
  data() {
    return {
      isRequired: false,
      hidden: false,
      id: '',
      type: 'ehs_hazop_rectification',
      file: null,
      limitNum: 1,
      formLabelWidth: '80px',
      fileList: [],

      total: 0,
      list: null,
      listLoading: true,
      editList: null,
      nodeId1: null,
      suggestMeasure1: null,
      sortable: null,
      nodeId: '',
      oldList: [],
      newList: [],

      // 参数条件
      listQuery: {
        // 获取URL参数
        nodeId: this.$route.query.nodeId,
        adoptId: this.$route.query.adoptId,
        adoptInfo: this.$route.query.adoptInfo,
      },
      temp: {
        id: undefined,
        nodeId: '',
        adoptId: '',
        rectifyMeasure: '',
        rectifySituation: '',
        approvalDate: '',
        approvalOpinion: '',
        status: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      //dialogDetailVisible: false,
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '明细'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        //timestamp: [{ type: 'analysisDate', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
       },
      downloadLoading: false,
    }
  },
  created() { 
    this.fechData()
  },
  methods: {
    fechData() {
      rectificationList(this.listQuery).then(response => {
        if (this.listQuery.nodeId === undefined) {
        alert('请先在危险性分析列表选择节点！')
        }
        this.listLoading = true
        this.list = response.ehsHazopRectificationList
        this.showList = response.ehsHazopRectificationList
        this.listLoading = false
        this.total = response.count
      })
    },
   
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const nodeId1 = this.$route.query.nodeId
        if (this.file == null) {
          this.temp.author = 'vue-element-admin'
          const query =
          { nodeId1: nodeId1,
            rectifyMeasure: this.temp.rectifyMeasure }
          addRectification(query).then(() => {
            this.list.unshift(this.temp.nodeId1)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          } else{
          this.temp.author = 'vue-element-admin'
          const query =
          { fileName: this.file.name, 
            fileId: this.file.filesId,
            nodeId1: nodeId1,
            rectifyMeasure: this.temp.rectifyMeasure }
          addRectification(query).then(() => {
            this.list.unshift(this.temp.nodeId1)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          }
          location.reload() 
        }
      })
    },

    handlegetFile(row) {
      
      this.id = row.id
      this.type = 'ehs_hazop_rectification'

      const query = { id: this.id, type: this.type }
      console.log('query is  ' + query)
      // 获取附件名称
      getFileName(query).then(response => {
        this.file = response.file
        console.log('MMMMMMMMMMMMMMMMMMMMMMMM' + this.file)
        const url = 'http://localhost:8080/ehs_files/getfile?id=' + this.id + '&type=' + this.type // 创建下载链接
        const link = document.createElement('a') // 创建a标签
        link.style.display = 'none' // 将a标签隐藏
        link.href = url // 给a标签添加下载链接
        link.setAttribute('download', this.file.filename) // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
        document.body.appendChild(link)
        link.click() // 执行a标签
      })
    },

    handleChange() {

    },
    uploadfile(response, file, fileList) {
      this.file = response.file
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        rectifyMeasure: '',
        approvalDate: '',
        approvalOpinion: '',
        status: ''
      }
    },

    showReviewer() {
    },

    handleFilter() {
      this.fechData()
    },

    handleEdit(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
      this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const adoptId1 = this.$route.query.adoptId
            if (this.file == null) {
              const query = { id: query1.id,
              adoptId1: adoptId1,
              rectifyMeasure: query1.rectifyMeasure }
              editRectification(query).then(response => {
              this.obj = response
              this.id = response.id
            })
            }else{
              const query = { id: query1.id,
              fileName: this.file.name, 
              fileId: this.file.filesId,
              adoptId1: adoptId1,
              rectifyMeasure: query1.rectifyMeasure }
              editRectification(query).then(response => {
              this.obj = response
              this.id = response.id
            })
            }
            
            // 刷新页面
            location.reload()
          }
        })
      }
    },
    
    handleDelete(row) {
      // eslint-disable-next-line no-lone-blocks
      {
        this.$confirm('确定删除?', 'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            deleteRectification(row.id).then(response => {
            })
            this.fechData()
            this.$message({
              type: 'success',
              message: 'Delete succed!'
            })
          })
          .catch(err => { console.error(err) })
      }
    },

    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}

</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>